<template>
  <div ref="wrapper" id="list-scroll">
    <slot></slot>
  </div>
</template>

<script>
import BScroll from 'better-scroll'
export default {
  name: 'ListScroll',
  props: {
    probeType: {
      type: Number,
      default: 1
    },
    click: {
      type: Boolean,
      default: true
    },
    scrollX: {
      type: Boolean,
      default: true
    },
    listenScroll: {
      type: Boolean,
      default: false
    },
    scrollStart: {
      type: Boolean,
      default: false
    },
    scrollEnd: {
      type: Boolean,
      default: false
    },
    pullingUp: {
      type: Boolean,
      default: true
    },
    pullingDown: {
      type: Boolean,
      default: true
    },
    scrollData: {
      required: true,
      type: Array
    }
  },
  data() {
    return {
      instance: null
    }
  },
  watch: {
    scrollData() {
      this.$nextTick(() => {
        this.instance.refresh()
      })
    }
  },
  mounted() {
    this.initScroll()
  },
  methods: {
    initScroll() {
      if (!this.$refs.wrapper) return
      this.instance = new BScroll(this.$refs.wrapper, {
        probeType: this.probeType,
        click: this.click,
        scrollX: this.scrollX,
        pullDownRefresh: true,
        pullUpLoad: true
      })

      if (this.listenScroll) {
        this.instance.on('scroll', position => {
          this.$emit('scroll', position)
        })
      }

      if (this.scrollStart) {
        this.instance.on('scrollStart', () => {
          this.$emit('scrollStart')
        })
      }

      if (this.scrollEnd) {
        this.instance.on('scrollEnd', () => {
          this.$emit('scrollEnd')
        })
      }

      if (this.pullingUp) {
        this.instance.on('pullingUp', () => {
          this.$emit('pullingUp')
          this.instance.finishPullUp()
        })
      }

      if (this.pullingDown) {
        this.instance.on('pullingDown', () => {
          this.$emit('pullingDown')
          this.instance.finishPullDown()
        })
      }

      this.instance.on('destroy', () => {
        this.$emit('destroy')
      })
    },

    disabled() {
      this.instance && this.instance.disabled()
    },

    refresh() {
      this.instance && this.instance.refresh()
    },

    scrollTo() {
      this.instance && this.instance.scrollTo.apply(this.instance, arguments)
    },

    scrollToElement() {
      this.instance &&
        this.instance.scrollToElement.apply(this.instance, arguments)
    }
  }
}
</script>

<style lang="less" scoped>
#list-scroll {
  width: 100%;
  height: 100%;
  overflow: hidden;
}
</style>
